package com.onesatoshi.mm.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class SettingDao {

    private DBHelp dbHelp;
    private SQLiteDatabase db;

    public SettingDao(Context context) {
        dbHelp = new DBHelp(context);
    }

    public void save(Setting setting) {
        db = dbHelp.getWritableDatabase();
        String sql = "insert into t_setting(property, value, status) values(?,?,?)";
        db.execSQL(sql, new String[]{setting.getProperty(), setting.getValue(), setting.getStatus()});
        db.close();
    }

    public void update(Setting setting) {
        db = dbHelp.getWritableDatabase();
        String sql = "update t_setting set property = ?, value = ?, status=? where _id = ?";
        db.execSQL(sql, new Object[]{setting.getProperty(), setting.getValue(), setting.getStatus(), setting.getId()});
        db.close();
    }

    public void del(int id) {
        db = dbHelp.getWritableDatabase();
        String sql = "delete from t_setting where _id = ?";
        db.execSQL(sql, new Object[]{id});
        db.close();
    }

    public List<Setting> findAll() {
        List<Setting> list = new ArrayList<Setting>();

        db = dbHelp.getReadableDatabase();
        String sql = "select _id, property, value, status from t_setting";
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            Setting setting = new Setting();
            setting.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            setting.setProperty(cursor.getString(cursor.getColumnIndex("property")));
            setting.setValue(cursor.getString(cursor.getColumnIndex("value")));
            setting.setStatus(cursor.getString(cursor.getColumnIndex("status")));
            list.add(setting);
        }
        db.close();
        return list;
    }

    public Setting findByProperty(String property) {
        Setting setting = null;
        db = dbHelp.getReadableDatabase();
        String sql = "select _id, property, value, status from t_setting where property = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{property});

        while (cursor.moveToNext()) {
            setting = new Setting();
            setting.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            setting.setProperty(cursor.getString(cursor.getColumnIndex("property")));
            setting.setValue(cursor.getString(cursor.getColumnIndex("value")));
            setting.setStatus(cursor.getString(cursor.getColumnIndex("status")));
        }

        db.close();
        return setting;
    }

}
